﻿using BySoft.Server.Business.UserCode;
using BySoft.Server.Common;
using BySoft.Server.Common.Entity;
using BySoft.Server.Common.Enum;
using BySoft.Server.Consts;
using BySoft.Web.Utility;
using OneSoft.EntityCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BySoft.Web.Site.BOM
{
    public partial class BOMChangeEdit : AuthBasePage
    {
        public DataTable BOMChangeMaterialDT
        {
            set { Session["BOMChangeMaterialDT"] = value; }
            get
            {
                if (Session["BOMChangeMaterialDT"] == null)
                {
                    return CreateDt();
                }
                else
                {
                    return (DataTable)Session["BOMChangeMaterialDT"];
                }
            }
        }
        public DataTable CreateDt()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("BOMChangeDetailID");
            dt.Columns.Add("BOMDetailID");
            dt.Columns.Add("MaterialID");//原料编号
            dt.Columns.Add("MaterialName");//原料名称
            dt.Columns.Add("Specifications");//规格
            dt.Columns.Add("Unit");//单位
            dt.Columns.Add("ChangeType");//变更类别
            dt.Columns.Add("Nums");//数量
            dt.Columns.Add("Remark");//备注
            dt.Columns.Add("IsNew");
            dt.Columns.Add("IsDel");
            return dt;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BOMChangeMaterialDT = null;
                InitData();
            }
            txtProductID.Attributes.Add("readonly", "true");
            txtProductName.Attributes.Add("readonly", "true");
            txtUnit.Attributes.Add("readonly", "true");
            Master.ValidationGroup = "gSubmit";
            UIHelper.RunScript(this.Page, "iframeAutoFit();");
        }

        private void InitData()
        {
            string id=HttpUtility.UrlDecode(UIHelper.GetQueryStringValue("id"));
            if (!string.IsNullOrEmpty(id))
            {
                DataTable dt = BsBOMChangeBusiness.GetDataById(id);
                if (dt != null && dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];
                    lblBOMChangeID.Text = CommonMethod.GetString(dr["BOMChangeID"]);
                    cpBillDate.Value = string.Format("{0:yyyy-MM-dd}", dr["BillDate"]);
                    txtProductID.Text = CommonMethod.GetString(dr["ProductID"]);
                    hdWorkOrderNo.Value = CommonMethod.GetString(dr["WorkOrderNo"]);
                    hdBOMID.Value = CommonMethod.GetString(dr["BOMID"]);
                    txtProductName.Text = CommonMethod.GetString(dr["ProductName"]);
                    txtUnit.Text = CommonMethod.GetString(dr["Unit"]);
                    
                    DataTable dtemp = BOMChangeMaterialDT.Copy();
                    foreach (DataRow drow in dt.Rows)
                    {
                        DataRow d = dtemp.NewRow();
                        d["BOMChangeDetailID"] = CommonMethod.GetString(dr["BOMChangeDetailID"]);
                        d["BOMDetailID"] = CommonMethod.GetString(dr["BOMDetailID"]);
                        d["MaterialID"] = CommonMethod.GetString(dr["MaterialID"]);
                        d["MaterialName"] = CommonMethod.GetString(dr["MaterialName"]);
                        d["Specifications"] = CommonMethod.GetString(dr["Specifications"]);
                        d["Unit"] = CommonMethod.GetString(dr["Unit"]);
                        d["ChangeType"] = CommonMethod.GetString(dr["ChangeType"]);
                        d["Nums"] = CommonMethod.GetString(dr["Nums"]);
                        d["Remark"] = CommonMethod.GetString(dr["Remark"]);
                        d["IsNew"] = "-1";
                        d["IsDel"] = "-1";
                        dtemp.Rows.Add(d);
                    }
                    BOMChangeMaterialDT = dtemp.Copy();
                }
            }
            BindMaterial();
        }

        private void BindMaterial()
        {
            DataView dv = new DataView(BOMChangeMaterialDT);
            dv.RowFilter = " IsDel <> '1' ";
            DataTable dt = dv.ToTable();
            dt.Columns.Add("OrderNum");
            if (dt != null && dt.Rows.Count > 0)
            {
                int index = 1;
                foreach (DataRow dr in dt.Rows)
                {
                    dr["OrderNum"] = index;
                    index++;
                }
                grdResult.DataSource = dt;
                grdResult.DataBind();
            }
            else
            {
                UIHelper.BindEmptyGridView(grdResult, dt);
            }
            UIHelper.RunScript(this.UpdatePanel4, "iframeAutoFit();");
        }


        private void AddMaterial()
        {
            BOMChangeMaterialDT = GetAddMaterial(BOMChangeMaterialDT).Copy();
        }

        private DataTable GetAddMaterial(DataTable dt)
        {
            DataTable dtTemp = dt.Copy();
            foreach (GridViewRow gvr in grdResult.Rows)
            {
                if (gvr.RowType == DataControlRowType.DataRow)
                {
                    Label lblBOMChangeDetailID = gvr.FindControl("lblBOMChangeDetailID") as Label;
                    Label lblBOMDetailID = gvr.FindControl("lblBOMDetailID") as Label;
                    Label lblMaterialID = gvr.FindControl("lblMaterialID") as Label;
                    Label lblMaterialName = gvr.FindControl("lblMaterialName") as Label;
                    Label lblSpecifications = gvr.FindControl("lblSpecifications") as Label;
                    Label lblUnit = gvr.FindControl("lblUnit") as Label;
                    DropDownList ddlChangeType = gvr.FindControl("ddlChangeType") as DropDownList;
                    TextBox txtNums = gvr.FindControl("txtNums") as TextBox;
                    TextBox txtRemark = gvr.FindControl("txtRemark") as TextBox;
                    string BOMDetailID = CommonMethod.GetString(lblBOMDetailID.Text);


                    DataRow[] drs = dtTemp.Select("BOMDetailID='" + BOMDetailID + "'");
                    if (drs.Length > 0)
                    {
                        drs[0]["BOMChangeDetailID"] = GetGridViewString(lblBOMChangeDetailID);
                        drs[0]["BOMDetailID"] = GetGridViewString(lblBOMDetailID);
                        drs[0]["MaterialID"] = GetGridViewString(lblMaterialID);
                        drs[0]["MaterialName"] = GetGridViewString(lblMaterialName);
                        drs[0]["Specifications"] = GetGridViewString(lblSpecifications);
                        drs[0]["Unit"] = GetGridViewString(lblUnit);
                        drs[0]["ChangeType"] = GetGridViewString(ddlChangeType);
                        drs[0]["Nums"] = GetGridViewString(txtNums);
                        drs[0]["Remark"] = GetGridViewString(txtRemark);
                    }
                }
            }
            return dtTemp;
        }


        protected void btnHidden_Click(object sender, EventArgs e)
        {
            AddMaterial();
            BindMaterial();
        }

        protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
                Button btnDel = (Button)e.Row.FindControl("btnDel");
                if (ibtn != null)
                {
                    ibtn.OnClientClick = "ShowTopConfirm('提示信息','" + Message.ConfirmDelete + "','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
                }
                DropDownList ddlChangeType = (DropDownList)e.Row.FindControl("ddlChangeType");
                BindParameterForListControl("ChangeType", ddlChangeType);
                UIHelper.InsertFirstItem(ddlChangeType);
                string ChangeType = ((DataTable)((GridView)sender).DataSource).Rows[e.Row.RowIndex]["ChangeType"].ToString().Trim();
                if (!string.IsNullOrEmpty(ChangeType))
                {
                    ddlChangeType.SelectedValue = ChangeType;
                }
            }
        }

        protected void grdResult_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strCode = e.CommandArgument.ToString();
            string[] strs = strCode.Split(',');
            switch (e.CommandName)
            {
                case "del":
                    AddMaterial();
                    DataTable dt = BOMChangeMaterialDT.Copy();
                    DataRow[] dr = dt.Select("BOMDetailID='" + strCode.Trim() + "'");
                    if (dr != null && dr.Length > 0)
                    {
                        dr[0]["IsDel"] = "1";
                    }
                    BOMChangeMaterialDT = dt.Copy();
                    BindMaterial();
                    UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);
                    break;
                default:
                    break;
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!ValidateData())
            {
                return;
            }
            try
            {
                if (string.IsNullOrEmpty(CurrentUser.UserID))
                {
                    UIHelper.AlertMessage(this.Page, "等待时间太久，请重新填写！");
                    return;
                }
                if (!string.IsNullOrEmpty(this.lblBOMChangeID.Text.Trim()))
                {
                    BsBomchangeEntity entity = new BsBomchangeEntity();
                    entity.BOMChangeID = GetString(lblBOMChangeID);
                    entity.BillDate = GetDateTime(cpBillDate);
                    entity.BOMID = GetString(hdBOMID);
                    entity.WorkOrderNo = GetString(hdWorkOrderNo);
                    entity.ProductID = GetString(txtProductID);
                    entity.ModifyDate = DateTime.Now;
                    entity.ModifyUserID = CurrentUser.UserID;
                    entity.ModifyUserName = CurrentUser.UserName;


                    if (BsBOMChangeBusiness.SaveOrUpdate(entity, BOMChangeMaterialDT, "Update"))
                    {
                        base.LogAction(BaseEnum.ActionType.Modify, entity.BOMID, true, null, new EntityBase[] { entity });
                        UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "../BOM/BOMChangeList.aspx");
                    }
                    else
                    {
                        UIHelper.AlertMessage(this.Page, Message.SaveFail);
                    }
                }
            }
            catch (Exception ex)
            {
                UIHelper.AlertMessage(this.Page, FomatString(ex.Message.ToString()));
            }
        }

        private bool ValidateData()
        {
            AddMaterial();
            DataView dv = new DataView(BOMChangeMaterialDT);
            dv.RowFilter = " IsDel <> '1' ";
            DataTable dt = dv.ToTable();
            if (dt == null || dt.Rows.Count <= 0)
            {
                UIHelper.AlertMessage(this.Page, "请添加原料明细！");
                return false;
            }
            return true;
        }

    }
}